package com.qf.mybatis.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MybatisSqlSessionUtils {
    //类级别成员变量SqlSessionFactory。好处，全局唯一
    private static SqlSessionFactory sqlSessionFactory;
    //创建ThreadLocal对象，该对象用于保存线程私有的数据
    private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();

    /*
     * 通过静态代码块初始化类级别得成员变量
     * 静态代码块仅在jvm加载class时执行一次
     * */
    static {
        try {
            InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
            SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
            sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /*
     * 获取sqlSession对象
     * */
    public static SqlSession getSqlSession() {
        //先检查当前线程是否曾经获取过SqlSession对象如果已经获取过直接使用
        SqlSession sqlSession = threadLocal.get();
        if (sqlSession != null) {
            return sqlSession;
        }
        //如果当前线程没有获取过SqlSession对象，创建一个新的，并保存起来
        sqlSession = sqlSessionFactory.openSession();//该方法每次调用都会新创建一个sqlSession
        threadLocal.set(sqlSession);//新创建的sqlSession对象保存到threadLocal对象中
        return sqlSession;
    }

    /*
     * 提交事务
     * */
    public static void commit() {
        //获取当前线程得SqlSession对象
        SqlSession sqlSession = getSqlSession();
        sqlSession.commit();
        //关闭当前线程sqlSession对象
        closeSqlSession();
    }

    private static void closeSqlSession() {
        //获取当前线程得SqlSession对象
        SqlSession sqlSession = getSqlSession();
        sqlSession.close();
    }

    /*
     * 回滚事务
     * */
    public static void rollback() {
        SqlSession sqlSession = getSqlSession();
        sqlSession.rollback();
        closeSqlSession();
    }

    public static <T> T getMapper(Class<T> clazz) {
        SqlSession sqlSession = getSqlSession();
        T mapper = sqlSession.getMapper(clazz);
        return mapper;
    }
}

  /*  public static SqlSession SSU() {
        //把mybatis-config.xml转换成输入流对象
        InputStream inputStream = null;
        SqlSession sqlSession = null;
        try {
            inputStream = Resources.getResourceAsStream("mybatis-config.xml");
            //创建一个SqlSessionFactoryBuilder对象
            SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
            //利用sqlSessionFactory 对象可以创建SqlSession对象
            SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
            //核心对象 SqlSession
            sqlSession = sqlSessionFactory.openSession();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sqlSession;
    }*/

